package com.winit.ogg.manager;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.base.bean.LoginUser;
import com.winit.common.util.*;
import com.winit.ogg.bean.Authorize;
import com.winit.ogg.util.TomUtil;
import com.winit.pms.model.ChangeLog;
import com.winit.pms.repository.PmsRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangjian on 17/8/28.
 */
@Component
public class OggManager {

    private static Logger logger = LoggerFactory.getLogger(OggManager.class);

    @Autowired
    private PmsRepository pmsRepository;

    @Autowired
    private PTServiceImpl operateService;

    @Value("${beetle_api_url}")
    private String beetle_api_url;
    @Value("${shell_path}")
    private String SHELL_PATH;

    //获取操作状态
    public Authorize getStatus() {
        Authorize authorize = JSONFileUtil.getFileJsonForBean(Constants.AUTHORIZE_FILE_PATH, Authorize.class);
        if (authorize == null) {
            authorize = new Authorize();
        }
        return authorize;
    }

    public Map<String, Object> cleanRedis() {
        Map<String, Object> map = ShellRunUtil.runCmds("source /etc/profile && cd " + SHELL_PATH + " && bash beetle_clean_redis.sh");
        logger.info("com.winit.ogg.manager.OggManager.cleanRedis map=" + map);
        return map;
    }

    //进行操作
    public synchronized Map toDo(LoginUser userInfo, String type) {
        Map<String, Object> rtnMap = new HashMap<String, Object>();
        Authorize authorize = JSONFileUtil.getFileJsonForBean(Constants.AUTHORIZE_FILE_PATH, Authorize.class);
        if (authorize == null) {
            authorize = new Authorize();
        }

        if ("auth_qa".equals(type)) {
            authorize.setAuth_qa(true);
            LogUtil.operateLog(userInfo, LogUtil.OperateType.QA_AUTHORIZE);
        } else if ("auth_ops".equals(type)) {
            authorize.setAuth_ops(true);
            updateTomConfig(true);
            LogUtil.operateLog(userInfo, LogUtil.OperateType.OPS_AUTHORIZE);
        } else if ("cancel_qa".equals(type)) {
            authorize.setAuth_qa(false);
            LogUtil.operateLog(userInfo, LogUtil.OperateType.CALCEL_QA_AUTHORIZE);
        } else if ("cancel_ops".equals(type)) {
            authorize.setAuth_ops(false);
            LogUtil.operateLog(userInfo, LogUtil.OperateType.CALCEL_OPS_AUTHORIZE);
        } else if ("cancel_all".equals(type)) {
            authorize.setAuth_qa(false);
            authorize.setAuth_ops(false);
            LogUtil.operateLog(userInfo, LogUtil.OperateType.CALCEL_ALL_AUTHORIZE);
        } else if ("start_ogg".equals(type) || "start_white".equals(type)) {
            if (!authorize.isAuth_ops() || !authorize.isAuth_qa()) {
                rtnMap.put("code", "1");
                rtnMap.put("desc", "必须qa和ops授权后才能才做ogg服务");
                return rtnMap;
            }
            if (authorize.isOgg_status()) {
                rtnMap.put("code", "1");
                rtnMap.put("desc", "同步服务正在运行,请稍后！");
                return rtnMap;
            }
            authorize.setOgg_status(true);
            if ("start_white".equals(type)) {
                authorize.setType("white");
            } else {
                authorize.setType("all");
            }

            LogUtil.operateLog(userInfo, LogUtil.OperateType.START_OGG);
            /*
            执行命令启动ogg
             */
//            Map map = operateService.start(beetle_api_url);

            Map map = operateService.start(type);
            if ("start_ogg".equals(type)) {
                updateTomConfig(true);
            }

            if ((Integer) map.get("code") != 0) {
                rtnMap.put("code", "1");
                rtnMap.put("desc", "启动ogg服务异常." + map.get("message"));
                return rtnMap;
            }
//        } else if ("stop_ogg".equals(type)) {
//            if (!authorize.isAuth_ops() || !authorize.isAuth_qa()) {
//                rtnMap.put("code", "1");
//                rtnMap.put("desc", "必须qa和ops授权后才能才做ogg服务");
//                return rtnMap;
//            }
//            authorize.setOgg_status(false);
//            LogUtil.operateLog(userInfo, LogUtil.OperateType.STOP_OGG);
//            /*
//            执行命令停止ogg
//             */
//            Map map = OggUtil.stopOGG(beetle_api_url);
//            if ((Integer) map.get("code") != 0) {
//                rtnMap.put("code", "1");
//                rtnMap.put("desc", "停止ogg服务异常." + map.get("message"));
//                return rtnMap;
//            }
        } else {
            rtnMap.put("code", "1");
            rtnMap.put("desc", "参数错误。type=" + type);
            return rtnMap;
        }

        boolean flag = JSONFileUtil.saveFileJson(Constants.AUTHORIZE_FILE_PATH, authorize);
        rtnMap.put("code", flag ? "0" : "1");
        rtnMap.put("desc", flag ? "" : "操作失败");
        return rtnMap;
    }

    public List<ChangeLog> getPmsChangeLog(String date) {
        logger.info("com.winit.ogg.manager.OggManager.getPmsChangeLog date:" + date);
        if (StringUtils.isEmpty(date)) {
            Date now = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = format.format(now);
        }
        List<ChangeLog> list = pmsRepository.findByCREATEDAfterOrUPDATEDAfter(date);
        logger.info("com.winit.ogg.manager.OggManager.getPmsChangeLog list:" + list.size());
        return list;
    }

    //OGG数据同步完成后,修改ogg状态,记录完成时间,修改tom配置文件,清理redis缓存
    public void afterOggComplete() {
        Authorize authorize = JSONFileUtil.getFileJsonForBean(Constants.AUTHORIZE_FILE_PATH, Authorize.class);
        if (!authorize.isOgg_status()) {
            logger.info("com.winit.ogg.manager.OggManager.afterOggComplete 未启动同步服务");
            return;
        }

        Map map = operateService.status();
        logger.info("com.winit.ogg.manager.OggManager.afterOggComplete map=" + map);
        if ((Integer) map.get("code") != 0) {
            logger.info("com.winit.ogg.manager.OggManager.afterOggComplete 查询服务状态失败");
            return;
        }
        if ("RUNNING".equals((String) map.get("message"))) {
            logger.info("com.winit.ogg.manager.OggManager.afterOggComplete 数据同步中");
            return;
        }
        //停ogg
//        OggUtil.stopOGG(beetle_api_url);
        //修改ogg状态,记录时间
//        Authorize authorize = JSONFileUtil.getFileJsonForBean(Constants.AUTHORIZE_FILE_PATH, Authorize.class);
        authorize.setOgg_status(false);
//        authorize.setAuth_qa(false);
//        authorize.setAuth_ops(false);
        Date now = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        authorize.setCompleteDate(format.format(now));
        JSONFileUtil.saveFileJson(Constants.AUTHORIZE_FILE_PATH, authorize);
        //修改tom配置文件
        if ("all".equals(authorize.getType())) {
            updateTomConfig(true);
        }
        //清理redis缓存
        try {
            String localIp = NetworkUtil.getLocalIp();
            if (!StringUtils.isEmpty(localIp)) {
                JSONObject jsonObject = HttpClientUtil.doGetForJson(beetle_api_url + "/beetle/uCloud/ogg/clean?ip=" + localIp);
                logger.info("com.winit.ogg.manager.OggManager.afterOggComplete clean redis,rtn:" + jsonObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //清空本地redis缓存
        cleanRedis();
    }

    public void updateTomConfig(boolean flag) {
        Authorize authorize = JSONFileUtil.getFileJsonForBean(Constants.AUTHORIZE_FILE_PATH, Authorize.class);
        authorize.setTom_flag(flag);
        JSONFileUtil.saveFileJson(Constants.AUTHORIZE_FILE_PATH, authorize);
        TomUtil.updateTomConfig(flag);
    }

    public void BudgetConfig() {
        logger.info("com.winit.ogg.manager.OggManager.BudgetConfig start");
        Map map = operateService.budget();
        logger.info("com.winit.ogg.manager.OggManager.BudgetConfig end . map = " + map);
    }
}
